package com.football.database;

import java.util.ArrayList;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

import com.football.model.Channel;

public class ChannelOperation {

	// Database fields
	private DataBaseWrapper dbHelper;
	private String[] CHANNEL_TABLE_COLUMNS = { DataBaseWrapper.CHANNEL_ID,
			DataBaseWrapper.CHANNEL_NAME, DataBaseWrapper.CHANNEL_URL,
			DataBaseWrapper.CHANNEL_DESCRIPTION };
	private SQLiteDatabase database;

	public ChannelOperation(Context context) {
		dbHelper = new DataBaseWrapper(context);
	}

	public void open() throws SQLException {
		database = dbHelper.getWritableDatabase();
	}

	public void close() {
		dbHelper.close();
	}

	public Channel addChannel(String name, String url, String des) {

		ContentValues values = new ContentValues();

		values.put(DataBaseWrapper.CHANNEL_NAME, name);
		values.put(DataBaseWrapper.CHANNEL_URL, url);
		values.put(DataBaseWrapper.CHANNEL_DESCRIPTION, des);

		long studId = database.insert(DataBaseWrapper.CHANNEL_TABLES, null,
				values);

		// now that the channel is created return it ...
		Cursor cursor = database.query(DataBaseWrapper.CHANNEL_TABLES,
				CHANNEL_TABLE_COLUMNS, DataBaseWrapper.CHANNEL_ID + " = "
						+ studId, null, null, null, null);

		cursor.moveToFirst();
		Channel newComment = parseChannel(cursor);
		cursor.close();
		return newComment;
	}

	private Channel parseChannel(Cursor cursor) {
		Channel channel = new Channel();
		channel.setId((cursor.getInt(0)));
		channel.setName(cursor.getString(1));
		channel.setUrl(cursor.getString(2));
		channel.setDescription(cursor.getString(3));
		return channel;
	}

	public void deleteChannel(Channel comment) {
		long id = comment.getId();
		System.out.println("Comment deleted with id: " + id);
		database.delete(DataBaseWrapper.CHANNEL_TABLES,
				DataBaseWrapper.CHANNEL_ID + " = " + id, null);
	}

	public void deleteChannel(Integer id) {
		System.out.println("Comment deleted with id: " + id);
		database.delete(DataBaseWrapper.CHANNEL_TABLES,
				DataBaseWrapper.CHANNEL_ID + " = " + id, null);
	}

	public ArrayList<Channel> getAllChannels() {
		ArrayList<Channel> channels = new ArrayList<Channel>();

		Cursor cursor = database.query(DataBaseWrapper.CHANNEL_TABLES,
				CHANNEL_TABLE_COLUMNS, null, null, null, null, null);

		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {
			Channel channel = parseChannel(cursor);
			channels.add(channel);
			cursor.moveToNext();
		}

		cursor.close();
		return channels;
	}
}